package net.slenderloris.touchclient;

import java.io.IOException;
import java.io.OutputStream;
import java.util.AbstractQueue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class BluetoothThread {

	public static final String TAG = BluetoothThread.class.getCanonicalName();
	
	private Thread mThread;
	private LinkedBlockingQueue<byte[]> mQueue = new LinkedBlockingQueue<byte[]>(1024);
	private BluetoothAdapter mBluetoothAdapter;
	private Handler mMainHandler;

	private UUID MY_UUID = UUID.fromString("01B99DA0-749F-11E2-BCFD-0800200C9A66");
	
	private class NetworkThreadRunnable implements Runnable {
		
		public void run() {
			
			OutputStream outputStream = null;
			
			synchronized (BluetoothThread.this) {
				try {
					Log.d(TAG, "Creating socket");
					outputStream = createOutputStream();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
			
			boolean running = true;
			
			while(running) {
				try {
					byte[] bytes = mQueue.take();
					if(bytes.length == 0) {
						Log.d(TAG,"Closing stream");
						outputStream.close();
						running = false;
					}
					else {
						Log.d(TAG,"writing " + bytes.length + " " + bytesToString(bytes));
						outputStream.write(bytes);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					running = false;
				} catch (IOException e) {
					e.printStackTrace();
					running = false;
				}
			}
			
		}

		private String bytesToString(byte[] bytes) {
			StringBuilder sb = new StringBuilder();
			for(byte b: bytes) {
				sb.append(b);
				sb.append(" ");
			}
			return sb.toString();
		};
		
	}
	
	public BluetoothThread() {
		mThread = new Thread(new NetworkThreadRunnable());
		//mThread.setPriority(Thread.MAX_PRIORITY);
		mThread.start();
		mMainHandler = new Handler();
	}

	private OutputStream createOutputStream() throws IOException {
		Log.d(TAG, "getting local device");
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		// remote MAC here:
		BluetoothDevice device = adapter.getRemoteDevice("00:02:72:37:6B:13");
		Log.d(TAG, "connecting to service");
		BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
		Log.d(TAG, "about to connect");
		socket.connect();
		Log.d(TAG, "Connected!");
		OutputStream stream = socket.getOutputStream();
		stream.write("Hello, world!".getBytes());
		return stream; 
	}
	
	public void write(byte[] bytes) {
		if(mQueue.remainingCapacity()>0) {
			mQueue.add(bytes);
		}
	}
	
	public void close() {
		mQueue.add(new byte[]{});
	}
	
}
